import os.path

import requests
from tqdm import tqdm

from xunter_utils.work_utils import work_logger


class BQGClient:
    def __init__(self):
        """
        初始化
        https://www.3bqg.cc/book/小说id/页数.html
        """
        self.url_temp = 'https://www.3bqg.cc/book'

    @work_logger()
    def send_request(self, url: str) -> requests.Response:
        """
        发送请求
        :param url: 请求地址
        :return: 请求的响应对象
        """

    def save(self, data: str) -> None:
        """
        存储函数
        :param data:
        :return:
        """

    def run(self, book_id: int, dir_path: str, pages: list | range):
        """
        解析函数
        :param book_id:
        :param dir_path:
        :param pages:
        :return:
        """


    def download(self, book_id: int, dir_path: str, pages: list | range) -> None:
        """
        下载指定小说的指定章节
        :param book_id: 小说的id
        :param dir_path: 小说保存目录
        :param pages: 要下载的章节列表
        :return: 无
        """
        # 判断保存目录是否存在，不存在则创建
        if not os.path.isdir(dir_path):
            os.mkdir(dir_path)  # mkdir 创建文件夹(文件夹的名字)

        # 获取要抓取的每页值
        for page in tqdm(pages):  # [1] range

            # 抓取每页文章书籍
            url = '%s/%d/%d.html' % (self.url_temp, book_id, page)
            # url = f'{self.url_temp}/{book_id}/{page}.html'
            res = requests.get(url)

            if res.status_code == 200:
                # 保存到对应的文件中
                with open(rf'{dir_path}/{page}.html', 'w', encoding='utf-8') as f:
                    f.write(res.text)


if __name__ == '__main__':
    client = BQGClient()
    # client.download(60417, '道诡异仙', range(1, 11))  # 抓取前10篇
    # client.download(60417, '道诡异仙', [20])  # 抓取1篇
    # client.download(60417, '道诡异仙', [21, 22, 24, 25])

